import { ModuleDisplayC } from "../module/ModuleDisplay";
import { ModuleMotionC, ModuleMotionData, Motion, MotionSheet } from "../module/ModuleMotion";
import { UIPool } from "../tool/UIPool";
import MotionEditorWindow_Generate from "../ui-generate/MotionEditor/MotionEditorWindow_generate";
import MotionShortcut_Generate from "../ui-generate/MotionEditor/MotionShortcut_generate";
import { CreateMotionWindow } from "./CreateMotionWindow";
import { MotionSheetElement } from "./MotionSheetElement";
import SheetAnimation_Generate from "../ui-generate/MotionEditor/SheetAnimation_generate";
import SheetArea_Generate from "../ui-generate/MotionEditor/SheetArea_generate";
import SheetEffect_Generate from "../ui-generate/MotionEditor/SheetEffect_generate";
import SheetSound_Generate from "../ui-generate/MotionEditor/SheetSound_generate";
import SheetDisplacement_Generate from "../ui-generate/MotionEditor/SheetDisplacement_generate";
import SheetEmit_Generate from "../ui-generate/MotionEditor/SheetEmit_generate";
import SheetLevitate_Generate from "../ui-generate/MotionEditor/SheetLevitate_generate";
import SheetBreaking_Generate from "../ui-generate/MotionEditor/SheetBreaking_generate";
import SheetFlash_Generate from "../ui-generate/MotionEditor/SheetFlash_generate";
import SheetCameraTransform_Generate from "../ui-generate/MotionEditor/SheetCameraTransform_generate";
import SheetCameraEase_Generate from "../ui-generate/MotionEditor/SheetCameraEase_generate";
import SheetInvisible_Generate from "../ui-generate/MotionEditor/SheetInvisible_generate";
import SheetBuff_Generate from "../ui-generate/MotionEditor/SheetBuff_generate";
import SheetSpawnAroundBuff_Generate from "../ui-generate/MotionEditor/SheetSpawnAroundBuff_generate";
import SheetSlotChange_Generate from "../ui-generate/MotionEditor/SheetSlotChange_generate";
import SheetCounter_Generate from "../ui-generate/MotionEditor/SheetCounter_generate";

enum EnumDataType {
    number,
    string,
    numberArray,
}

class InputField {
    public data:MotionSheet

    constructor(private inputFiled:mw.InputBox,public dataPath:string[],public dataType:EnumDataType,public arrayIndex?:number) {
        this.inputFiled = inputFiled
        this.dataPath = dataPath
        this.dataType = dataType
        this.arrayIndex = arrayIndex
    }

    resetMotionSet(data:MotionSheet){
        this.data = data
    } 

    read(){
        let data:Object = this.data
        for (const pathItem of this.dataPath) {
            data = data[pathItem]
            if(data == undefined) {
                this.inputFiled.text = ''
                return
            }
        }
        if(this.dataType == EnumDataType.numberArray){
            this.inputFiled.text = data[this.arrayIndex].toString()
        }
        else{
            this.inputFiled.text = data.toString()
        }mw.HumanoidSlotType.Root
    }

    write(dataRef:MotionSheet){
        if(this.inputFiled.text == '') return

        let tempRef = dataRef
        for (let i = 0; i < this.dataPath.length-1; i++) {
            let path = this.dataPath[i]
            if(!tempRef[path]) tempRef[path] = {}
            tempRef = tempRef[path]
        }

        let lastIndexName = this.dataPath[this.dataPath.length-1]
        if(this.dataType == EnumDataType.number){
            tempRef[lastIndexName] = Number(this.inputFiled.text)
        }
        else if(this.dataType == EnumDataType.string){
            tempRef[lastIndexName] = this.inputFiled.text
        }
        else if(this.dataType == EnumDataType.numberArray){
            if(!tempRef[lastIndexName]) tempRef[lastIndexName] = []

            tempRef[lastIndexName][this.arrayIndex] = Number(this.inputFiled.text)
        }
    }
}

export class MotionEditorWindow extends MotionEditorWindow_Generate{
    private sheetUIPool:UIPool<MotionSheetElement> = new UIPool<MotionSheetElement>()
    private inputFieldArray:InputField[] = []

    private md:ModuleMotionC
    private mdData:ModuleMotionData
    private displayMD:ModuleDisplayC

    private selectedMotion:Motion|undefined
    private selectedIndex = 0

    private selected_effect_once = false

    private motionShortcutPool:UIPool<MotionShortcut> = new UIPool<MotionShortcut>()

    private animationSheet:SheetAnimation_Generate
    private effectSheet:SheetEffect_Generate
    private areaSheet:SheetArea_Generate
    private soundSheet:SheetSound_Generate
    private displacementSheet:SheetDisplacement_Generate
    private emitSheet:SheetEmit_Generate
    private levitateSheet:SheetLevitate_Generate
    private breakingSheet:SheetBreaking_Generate
    private flashSheet:SheetFlash_Generate
    private cameraTransformSheet:SheetCameraTransform_Generate
    private cameraEaseSheet:SheetCameraEase_Generate
    private invisibleSheet:SheetInvisible_Generate
    private buffSheet:SheetBuff_Generate 
    private aroundBuffSheet:SheetSpawnAroundBuff_Generate
    private slotChangeSheet:SheetSlotChange_Generate
    private counterSheet:SheetCounter_Generate

    private clearSingleSheetInfo(sheetUI:mw.UIScript){ 
        for(let i = 0;i < sheetUI.rootCanvas.getChildrenCount();i++){
            let child = sheetUI.rootCanvas.getChildAt(i)
            if(!(child instanceof mw.InputBox)) continue
            (child as mw.InputBox).text = ''
        }
    }

    private bindButtonClearFunction(ui:mw.UIScript){
        let btn_close = <mw.Button>ui.rootCanvas.getChildByName('btn_clear')
        if(!btn_close) return
        btn_close.onClicked.add(()=>{
            this.clearSingleSheetInfo(ui)
        })
    }

    async onStart(){
        this.md = ModuleService.getModule(ModuleMotionC)
        this.displayMD = ModuleService.getModule(ModuleDisplayC)
        this.mdData = DataCenterC.getData(ModuleMotionData)

        this.motionShortcutPool.setCreator(()=>{
            let item = mw.UIService.create(MotionShortcut)
            this.con_motion_name_array.addChild(item.uiObject)
            item.uiObject.size = new mw.Vector2(190,60)
            return item
        })

        this.animationSheet = mw.UIService.create(SheetAnimation_Generate)
        this.con_detail_new.addChild(this.animationSheet.uiObject)
        this.bindButtonClearFunction(this.animationSheet)

        this.areaSheet = mw.UIService.create(SheetArea_Generate)
        this.con_detail_new.addChild(this.areaSheet.uiObject)
        this.bindButtonClearFunction(this.areaSheet)

        this.effectSheet = mw.UIService.create(SheetEffect_Generate)
        this.con_detail_new.addChild(this.effectSheet.uiObject)
        this.bindButtonClearFunction(this.effectSheet)

        this.soundSheet = mw.UIService.create(SheetSound_Generate)
        this.con_detail_new.addChild(this.soundSheet.uiObject)
        this.bindButtonClearFunction(this.soundSheet)

        this.displacementSheet = mw.UIService.create(SheetDisplacement_Generate)
        this.con_detail_new.addChild(this.displacementSheet.uiObject)
        this.bindButtonClearFunction(this.displacementSheet)

        this.emitSheet = mw.UIService.create(SheetEmit_Generate)
        this.con_detail_new.addChild(this.emitSheet.uiObject)
        this.bindButtonClearFunction(this.emitSheet)

        this.levitateSheet = mw.UIService.create(SheetLevitate_Generate)
        this.con_detail_new.addChild(this.levitateSheet.uiObject)
        this.bindButtonClearFunction(this.levitateSheet)

        this.breakingSheet = mw.UIService.create(SheetBreaking_Generate)
        this.con_detail_new.addChild(this.breakingSheet.uiObject)
        this.bindButtonClearFunction(this.breakingSheet)

        this.flashSheet = mw.UIService.create(SheetFlash_Generate)
        this.con_detail_new.addChild(this.flashSheet.uiObject)
        this.bindButtonClearFunction(this.flashSheet)

        this.cameraTransformSheet = mw.UIService.create(SheetCameraTransform_Generate)
        this.con_detail_new.addChild(this.cameraTransformSheet.uiObject)
        this.bindButtonClearFunction(this.cameraTransformSheet)

        this.cameraEaseSheet = mw.UIService.create(SheetCameraEase_Generate)
        this.con_detail_new.addChild(this.cameraEaseSheet.uiObject)
        this.bindButtonClearFunction(this.cameraEaseSheet)

        this.invisibleSheet = mw.UIService.create(SheetInvisible_Generate)
        this.con_detail_new.addChild(this.invisibleSheet.uiObject)
        this.bindButtonClearFunction(this.invisibleSheet)

        this.buffSheet = mw.UIService.create(SheetBuff_Generate)
        this.con_detail_new.addChild(this.buffSheet.uiObject)
        this.bindButtonClearFunction(this.buffSheet)

        this.aroundBuffSheet = mw.UIService.create(SheetSpawnAroundBuff_Generate)
        this.con_detail_new.addChild(this.aroundBuffSheet.uiObject)
        this.bindButtonClearFunction(this.aroundBuffSheet)

        this.slotChangeSheet = mw.UIService.create(SheetSlotChange_Generate)
        this.con_detail_new.addChild(this.slotChangeSheet.uiObject)
        this.bindButtonClearFunction(this.slotChangeSheet)

        this.counterSheet = mw.UIService.create(SheetCounter_Generate)
        this.con_detail_new.addChild(this.counterSheet.uiObject)
        this.bindButtonClearFunction(this.counterSheet)

        this.input_control_character_id.onTextCommitted.add(()=>{
            // let result = this.displayMD.resetControlCharacter(this.input_control_character_id.text)
            // if(!result) this.input_control_character_id.text = this.displayMD.displayObj.
        })

        this.btn_area_effect_once.onClicked.add(this.onEffectOnceClick.bind(this))
        this.input_frame_rate.onTextCommitted.add(this.onFrameRateChanged.bind(this))
        this.btn_add.onPressed.add(()=>{
            if(this.md.currentSelectedSheet == undefined) return
            let count = this.md.getMotionCount(this.md.currentSelectedSheet)
            this.md.initMotion(this.md.currentSelectedSheet,count + 1)
        })
        this.btn_minus.onPressed.add(()=>{
            if(this.md.currentSelectedSheet == undefined) return
            let count = this.md.getMotionCount(this.md.currentSelectedSheet)
            this.md.initMotion(this.md.currentSelectedSheet,Math.max(count - 1,1))
        })
        this.btn_play.onPressed.add(()=>{
            if(this.md.currentSelectedSheet == undefined) return

            this.saveCurrentSheetData()

            let page = this.md.currentSelectedSheet
            let data = this.mdData.sheets[page]
            ModuleService.getModule(ModuleDisplayC).play(data)
        })
        this.btn_create.onClicked.add(()=>{
            mw.UIService.show(CreateMotionWindow)
        })
        this.btn_reset_pos.onPressed.add(()=>{
            this.displayMD.resetPosition()
        })
        InputUtil.onKeyDown(mw.Keys.C,()=>{ this.md.copySheetData(this.selectedIndex) })
        InputUtil.onKeyDown(mw.Keys.V,()=>{ this.md.pasteSheetData(this.selectedIndex) })
        InputUtil.onKeyDown(mw.Keys.X,()=>{
            this.md.copySheetData(this.selectedIndex)
            this.md.clearSheetData(this.selectedIndex)
        })

        this.input_motion_move_speed.onTextCommitted.add(txt=>{
            this.md.setMotionMoveSpeed(this.selectedMotion.name,Number(txt))
        })

        this.areaSheet.btn_use_obb.onPressed.add(()=>{
            this.areaSheet.input_obb_x.text = ('0')
            this.areaSheet.input_obb_y.text = ('0')
            this.areaSheet.input_obb_z.text = ('0')
            this.areaSheet.input_obb_x_rot.text = ('0')
            this.areaSheet.input_obb_y_rot.text = ('0')
            this.areaSheet.input_obb_z_rot.text = ('0')
            this.areaSheet.input_obb_x_ext.text = ('1')
            this.areaSheet.input_obb_y_ext.text = ('1')
            this.areaSheet.input_obb_z_ext.text = ('1')
        })

        this.sheetUIPool.setCreator(()=>{
            let item = mw.UIService.create(MotionSheetElement)
            this.canvas_sheet.addChild(item.uiObject)
            item.uiObject.size = (new mw.Vector2(30,300))
            return item
        })

        // 动画
        this.inputFieldArray.push(
            new InputField(this.animationSheet.input_anim_id,['anim','guid'],EnumDataType.string),
            new InputField(this.animationSheet.input_anim_count,['anim','count'],EnumDataType.number),
        )

        // 特效
        this.inputFieldArray.push(
            new InputField(this.effectSheet.input_eff_guid,['eff','guid'],EnumDataType.string),
            new InputField(this.effectSheet.input_eff_socket,['eff','socket'],EnumDataType.number),
            new InputField(this.effectSheet.input_eff_pos_x,['eff','transform'],EnumDataType.numberArray,0),
            new InputField(this.effectSheet.input_eff_pos_y,['eff','transform'],EnumDataType.numberArray,1),
            new InputField(this.effectSheet.input_eff_pos_z,['eff','transform'],EnumDataType.numberArray,2),
            new InputField(this.effectSheet.input_eff_rot_x,['eff','transform'],EnumDataType.numberArray,3),
            new InputField(this.effectSheet.input_eff_rot_y,['eff','transform'],EnumDataType.numberArray,4),
            new InputField(this.effectSheet.input_eff_rot_z,['eff','transform'],EnumDataType.numberArray,5),
            new InputField(this.effectSheet.input_eff_sca_x,['eff','transform'],EnumDataType.numberArray,6),
            new InputField(this.effectSheet.input_eff_sca_y,['eff','transform'],EnumDataType.numberArray,7),
            new InputField(this.effectSheet.input_eff_sca_z,['eff','transform'],EnumDataType.numberArray,8),
            new InputField(this.effectSheet.input_eff_col_hex,['eff','color'],EnumDataType.string),
            new InputField(this.effectSheet.input_eff_projection,['eff','projection'],EnumDataType.number),
        )

        // 音效
        this.inputFieldArray.push(
            new InputField(this.soundSheet.input_sound_guid,['sound','guid'],EnumDataType.string),
            new InputField(this.soundSheet.input_sound_volume,['sound','volume'],EnumDataType.number),
        )

        // 位移
        this.inputFieldArray.push(
            new InputField(this.displacementSheet.input_disp_x,['displacement'],EnumDataType.numberArray,0),
            new InputField(this.displacementSheet.input_disp_y,['displacement'],EnumDataType.numberArray,1),
            new InputField(this.displacementSheet.input_disp_z,['displacement'],EnumDataType.numberArray,2)
        )

        // 判定
        this.inputFieldArray.push(
            new InputField(this.areaSheet.input_obb_x,['obb','transform'],EnumDataType.numberArray,0),
            new InputField(this.areaSheet.input_obb_y,['obb','transform'],EnumDataType.numberArray,1),
            new InputField(this.areaSheet.input_obb_z,['obb','transform'],EnumDataType.numberArray,2),

            new InputField(this.areaSheet.input_obb_x_rot,['obb','transform'],EnumDataType.numberArray,3),
            new InputField(this.areaSheet.input_obb_y_rot,['obb','transform'],EnumDataType.numberArray,4),
            new InputField(this.areaSheet.input_obb_z_rot,['obb','transform'],EnumDataType.numberArray,5),

            new InputField(this.areaSheet.input_obb_x_ext,['obb','transform'],EnumDataType.numberArray,6),
            new InputField(this.areaSheet.input_obb_y_ext,['obb','transform'],EnumDataType.numberArray,7),
            new InputField(this.areaSheet.input_obb_z_ext,['obb','transform'],EnumDataType.numberArray,8),

            new InputField(this.areaSheet.input_obb_damage_factor,['obb','damageFactor'],EnumDataType.number),

            new InputField(this.areaSheet.input_obb_effect_id,['obb','effectID'],EnumDataType.string),
            new InputField(this.areaSheet.input_obb_eff_scale_x,['obb','effectScale'],EnumDataType.numberArray,0),
            new InputField(this.areaSheet.input_obb_eff_scale_y,['obb','effectScale'],EnumDataType.numberArray,1),
            new InputField(this.areaSheet.input_obb_eff_scale_z,['obb','effectScale'],EnumDataType.numberArray,2),

            new InputField(this.areaSheet.input_obb_sound_id,['obb','soundID'],EnumDataType.string),

            new InputField(this.areaSheet.input_obb_control,['obb','control'],EnumDataType.number),
            new InputField(this.areaSheet.input_obb_repel,['obb','repel'],EnumDataType.number),
            new InputField(this.areaSheet.input_obb_levitate,['obb','levitate'],EnumDataType.number),
            new InputField(this.areaSheet.input_obb_eff_col_hex,['obb','effectColor'],EnumDataType.string),
            new InputField(this.areaSheet.input_obb_debuff_id,['obb','debuff'],EnumDataType.number),

            new InputField(this.areaSheet.input_obb_addition_attr_type,['obb','attrType'],EnumDataType.string),
            new InputField(this.areaSheet.input_obb_addition_attr_value,['obb','attrValue'],EnumDataType.string),
        )

        // 法术场
        this.inputFieldArray.push(
            // 特效ID
            new InputField(this.emitSheet.input_emit_effect_id,['emit','effectID'],EnumDataType.string),
            // 发射偏移
            new InputField(this.emitSheet.input_emit_offset_x,['emit','positionOffset'],EnumDataType.numberArray,0),
            new InputField(this.emitSheet.input_emit_offset_y,['emit','positionOffset'],EnumDataType.numberArray,1),
            new InputField(this.emitSheet.input_emit_offset_z,['emit','positionOffset'],EnumDataType.numberArray,2),
            // 位移增量
            new InputField(this.emitSheet.input_emit_trans_x,['emit','translate'],EnumDataType.numberArray,0),
            new InputField(this.emitSheet.input_emit_trans_y,['emit','translate'],EnumDataType.numberArray,1),
            new InputField(this.emitSheet.input_emit_trans_z,['emit','translate'],EnumDataType.numberArray,2),
            // 持续帧数
            new InputField(this.emitSheet.input_emit_life_frame,['emit','aliveFrame'],EnumDataType.number),
            // 特效缩放
            new InputField(this.emitSheet.input_emit_scale_x,['emit','scale'],EnumDataType.numberArray,0),
            new InputField(this.emitSheet.input_emit_scale_y,['emit','scale'],EnumDataType.numberArray,1),
            new InputField(this.emitSheet.input_emit_scale_z,['emit','scale'],EnumDataType.numberArray,2),
            // 发射旋转
            new InputField(this.emitSheet.input_emit_rotation_x,['emit','rotationOffset'],EnumDataType.numberArray,0),
            new InputField(this.emitSheet.input_emit_rotation_y,['emit','rotationOffset'],EnumDataType.numberArray,1),
            new InputField(this.emitSheet.input_emit_rotation_z,['emit','rotationOffset'],EnumDataType.numberArray,2),
            // 命中特效
            new InputField(this.emitSheet.input_emit_hit_eff_id,['emit','hitEffect'],EnumDataType.string),
            // 命中特效缩放
            new InputField(this.emitSheet.input_emit_hit_scale_x,['emit','hitEffectScale'],EnumDataType.numberArray,0),
            new InputField(this.emitSheet.input_emit_hit_scale_y,['emit','hitEffectScale'],EnumDataType.numberArray,1),
            new InputField(this.emitSheet.input_emit_hit_scale_z,['emit','hitEffectScale'],EnumDataType.numberArray,2),
            // 判定缩放
            new InputField(this.emitSheet.input_emit_area_scale_x,['emit','areaScale'],EnumDataType.numberArray,0),
            new InputField(this.emitSheet.input_emit_area_scale_y,['emit','areaScale'],EnumDataType.numberArray,1),
            new InputField(this.emitSheet.input_emit_area_scale_z,['emit','areaScale'],EnumDataType.numberArray,2),
            // 判定伤害系数
            new InputField(this.emitSheet.input_emit_hit_factor,['emit','hitDamageFactor'],EnumDataType.number),
            // 是否命中后销毁
            new InputField(this.emitSheet.input_emit_hit_disable,['emit','hitDisable'],EnumDataType.number),
            // 重复命中间隔
            new InputField(this.emitSheet.input_emit_hit_interval,['emit','hitInterval'],EnumDataType.number),
            // 重力
            new InputField(this.emitSheet.input_emit_gravity,['emit','gravity'],EnumDataType.number),
            // 索敌
            new InputField(this.emitSheet.input_lock_distance,['emit','lockDistance'],EnumDataType.number),
            new InputField(this.emitSheet.input_lock_type,['emit','trajectoryType'],EnumDataType.string),
            new InputField(this.emitSheet.input_lock_args,['emit','trajectoryArgs'],EnumDataType.string),
            // 附加属性
            new InputField(this.emitSheet.input_addition_attr_type,['emit','attrType'],EnumDataType.string),
            new InputField(this.emitSheet.input_addition_attr_value,['emit','attrValue'],EnumDataType.string),
            // 颜色
            new InputField(this.emitSheet.input_color,['emit','color'],EnumDataType.string),
        )

        // 浮空状态
        this.inputFieldArray.push(
            new InputField(this.levitateSheet.input_levitate_frame,['levitate'],EnumDataType.number)
        )
        // 瞬移判定范围
        this.inputFieldArray.push(
            new InputField(this.flashSheet.input_flash_range,['flashRange'],EnumDataType.number)
        )
        // 中断点
        this.inputFieldArray.push(
            new InputField(this.breakingSheet.input_breaking_point,['breakingPoint'],EnumDataType.number)
        )

        // 摄像机位移
        this.inputFieldArray.push(
            new InputField(this.cameraTransformSheet.input_camara_pos_x,['cameraTransform','pos'],EnumDataType.numberArray,0),
            new InputField(this.cameraTransformSheet.input_camara_pos_y,['cameraTransform','pos'],EnumDataType.numberArray,1),
            new InputField(this.cameraTransformSheet.input_camara_pos_z,['cameraTransform','pos'],EnumDataType.numberArray,2),
            new InputField(this.cameraTransformSheet.input_camara_rot_x,['cameraTransform','rot'],EnumDataType.numberArray,0),
            new InputField(this.cameraTransformSheet.input_camara_rot_y,['cameraTransform','rot'],EnumDataType.numberArray,1),
            new InputField(this.cameraTransformSheet.input_camara_rot_z,['cameraTransform','rot'],EnumDataType.numberArray,2)
        )

        // 摄像机平滑位移
        this.inputFieldArray.push(
            new InputField(this.cameraEaseSheet.input_cam_lerp_pos_x,['cameraLerpTransform','pos'],EnumDataType.numberArray,0),
            new InputField(this.cameraEaseSheet.input_cam_lerp_pos_y,['cameraLerpTransform','pos'],EnumDataType.numberArray,1),
            new InputField(this.cameraEaseSheet.input_cam_lerp_pos_z,['cameraLerpTransform','pos'],EnumDataType.numberArray,2),

            new InputField(this.cameraEaseSheet.input_cam_lerp_rot_x,['cameraLerpTransform','rot'],EnumDataType.numberArray,0),
            new InputField(this.cameraEaseSheet.input_cam_lerp_rot_y,['cameraLerpTransform','rot'],EnumDataType.numberArray,1),
            new InputField(this.cameraEaseSheet.input_cam_lerp_rot_z,['cameraLerpTransform','rot'],EnumDataType.numberArray,2),

            new InputField(this.cameraEaseSheet.input_cam_lerp_during,['cameraLerpTransform','during'],EnumDataType.number)
        )

        // 玩家隐身帧数
        this.inputFieldArray.push(
            new InputField(this.invisibleSheet.input_invisible_during,['invisibleDuring'],EnumDataType.number)
        )

        // 玩家产生buffID
        this.inputFieldArray.push(
            new InputField(this.buffSheet.input_spawn_buff,['spawnBuffID'],EnumDataType.number)
        )
            
        // 向周围派发buff
        this.inputFieldArray.push(
            new InputField(this.aroundBuffSheet.input_effect_buff_type,['spawnAroundBuff','effectType'],EnumDataType.number),
            new InputField(this.aroundBuffSheet.input_around_buff_id,['spawnAroundBuff','buffID'],EnumDataType.number),
            new InputField(this.aroundBuffSheet.input_around_buff_range,['spawnAroundBuff','range'],EnumDataType.number),
        )

        // 槽位变化
        this.inputFieldArray.push(
            new InputField(this.slotChangeSheet.input_slot_change,['slotChange'],EnumDataType.number),
        )

        // 反制帧数
        this.inputFieldArray.push(
            new InputField(this.counterSheet.input_Counter_during,['countDuring'],EnumDataType.number),
            new InputField(this.counterSheet.input_counter_contact_motion,['counterContactMotion'],EnumDataType.string),
            new InputField(this.counterSheet.input_counter_contact_motion_gather,['counterContactGatherMotion'],EnumDataType.string),
        )


        this.displayMD.onFrameChanged.add(this.refreshCurrentFrame,this)
        this.md.onMotionDataChanged.add(this.refreshData,this)
        this.md.onMotionDataChanged.add(this.refreshMotionList,this)

        this.btn_follow.onPressed.add(this.onUnlockCameraBtnPressed.bind(this));
        this.btn_opacity.onPressed.add(this.onOpacityClicked.bind(this))
        this.cameraEaseSheet.btn_recode_camera_trans_lerp.onPressed.add(this.onRecodeCameraTransformLerpClicked.bind(this))
        this.cameraTransformSheet.btn_recode_camera_trans.onPressed.add(this.onRecodeCameraTransformClicked.bind(this))

        this.refreshMotionList()
    }

    onShow(){
        this.refreshData()
        if(this.mdData.sheets[this.md.currentSelectedSheet].motionSheets.length > 0){
            this.onSheetClick(0)
        }
    }

    // 刷新全部数据
    private refreshData(){
        this.sheetUIPool.resetAll()

        if(this.md.currentSelectedSheet == undefined) return

        // 删除帧时
        if(this.selectedIndex > this.mdData.sheets[this.md.currentSelectedSheet].motionSheets.length - 1){
            this.selectedIndex = 0
        }

        this.selectedMotion = this.mdData.sheets[this.md.currentSelectedSheet]
        for (let i = 0; i < this.selectedMotion.motionSheets.length; i++) {
            let item = this.sheetUIPool.get()
            item.refresh(this.selectedMotion,i,this.onSheetClick,this)
        }
        // 总帧数
        this.txt_frame_count.text = this.selectedMotion.motionSheets.length.toString()
        // 是否只触发一次判定
        this.selected_effect_once = this.selectedMotion.areaEffectOnce || false
        this.btn_area_effect_once.normalImageColor = (this.selected_effect_once ? mw.LinearColor.green : mw.LinearColor.red)

        // motion移动速度
        if(this.selectedMotion.motionMoveSpeed){
            this.input_motion_move_speed.text = this.selectedMotion.motionMoveSpeed.toString()
        }else{
            this.input_motion_move_speed.text = ''
        }

        // 刷新详情面板
        let page = this.md.currentSelectedSheet
        if(!page) return
        let data = this.mdData.sheets[page].motionSheets[this.selectedIndex]
        this.refreshDetail(data)
    }

    // 点击 sheet
    private onSheetClick(index:number){
        this.saveCurrentSheetData()

        this.selectedIndex = index
        let page = this.md.currentSelectedSheet
        let data = this.mdData.sheets[page].motionSheets[this.selectedIndex]
        this.sheetUIPool.eachActive((index,item)=>{
            item.setSelected(index == this.selectedIndex)
        })
        this.refreshDetail(data)
    }

    // 设置详情面板
    private refreshDetail(data:MotionSheet){
        this.inputFieldArray.forEach(item=>{
            item.resetMotionSet(data)
            item.read()
        })
    }

    // 点击仅触发一次判定选项
    private onEffectOnceClick(){
        this.selected_effect_once = !this.selected_effect_once
        this.btn_area_effect_once.normalImageColor = (this.selected_effect_once ? mw.LinearColor.green : mw.LinearColor.red)
        this.md.setMotionAreaEffectOnce(this.md.currentSelectedSheet,this.selected_effect_once)
    }

    // 保存当前sheet
    private saveCurrentSheetData(){
        let newData = new MotionSheet()

        this.inputFieldArray.forEach(item=>{
            item.write(newData)
        })

        this.md.coverSheetData(this.selectedIndex,newData)
    }

    // 修改展示速度时
    private onFrameRateChanged(){
        ModuleService.getModule(ModuleDisplayC).changeFrameRate(Number(this.input_frame_rate.text))
    }

    // 刷新当前帧数
    private refreshCurrentFrame(frame:number){
        this.sheetUIPool.eachActive((index,item)=>{
            item.setFrameDisplay(frame == index)
        })
    }

    async onUnlockCameraBtnPressed(){
        if(this.img_following.visibility == mw.SlateVisibility.SelfHitTestInvisible){
            this.img_following.visibility = mw.SlateVisibility.Collapsed;
            this.displayMD.lockCamera();
        }else{
            this.img_following.visibility = mw.SlateVisibility.SelfHitTestInvisible;
            this.displayMD.cameraFollow();
        }
    }

    private opacity:boolean = false
    private onOpacityClicked(){
        this.opacity = !this.opacity
        let val =  this.opacity ? 0.2 : 1
        this.img_sheet_bg.renderOpacity = val
        this.sheetUIPool.eachActive((index,item)=>{
            item.uiObject.renderOpacity = val
        })
        this.img_detail.renderOpacity = val
        let childCount = this.con_detail_new.getChildrenCount()
        for (let index = 0; index < childCount; index++) {
            this.con_detail_new.getChildAt(index).renderOpacity = val
        }
        this.displayMD.addJump()
    }

    private onRecodeCameraTransformLerpClicked(){
        let [loc,rot] = this.displayMD.getCameraRelevantLocationFromPlayer()
        this.cameraEaseSheet.input_cam_lerp_pos_x.text = loc.x.toFixed(0)
        this.cameraEaseSheet.input_cam_lerp_pos_y.text = loc.y.toFixed(0)
        this.cameraEaseSheet.input_cam_lerp_pos_z.text = loc.z.toFixed(0)

        this.cameraEaseSheet.input_cam_lerp_rot_x.text = '0'
        this.cameraEaseSheet.input_cam_lerp_rot_y.text = rot.y.toFixed(0)
        this.cameraEaseSheet.input_cam_lerp_rot_z.text = rot.z.toFixed(0)

        this.cameraEaseSheet.input_cam_lerp_during.text = '10'
    }

    private onRecodeCameraTransformClicked(){
        let [loc,rot] = this.displayMD.getCameraRelevantLocationFromPlayer()
        this.cameraTransformSheet.input_camara_pos_x.text = loc.x.toFixed(0)
        this.cameraTransformSheet.input_camara_pos_y.text = loc.y.toFixed(0)
        this.cameraTransformSheet.input_camara_pos_z.text = loc.z.toFixed(0)

        this.cameraTransformSheet.input_camara_rot_x.text = rot.x.toFixed(0)
        this.cameraTransformSheet.input_camara_rot_y.text = rot.y.toFixed(0)
        this.cameraTransformSheet.input_camara_rot_z.text = rot.z.toFixed(0)
    }

    refreshMotionList(){
        this.txt_currentMotion.text = this.md.currentSelectedSheet

        this.motionShortcutPool.resetAll()
        let data = DataCenterC.getData(ModuleMotionData)
        for (let name in data.sheets) {
            let motion = data.sheets[name]
            let btn = this.motionShortcutPool.get()
            btn.setInfo(motion,this.onClickShortcut,this)
            btn.setSelected(this.md.currentSelectedSheet == name)
        }
    }

    private onClickShortcut(caller:MotionShortcut){
        this.saveCurrentSheetData()

        this.md.selectNewSheet(caller.motion.name)
    }
}

class MotionShortcut extends MotionShortcut_Generate{
    private func:(caller:MotionShortcut)=>void
    private caller:any
    motion:Motion

    onStart(){
        this.btn_func.onPressed.add(this.onClicked.bind(this))
        this.btn_delete.onPressed.add(this.deleteClicked.bind(this))
    }

    setInfo(motion:Motion,func:(caller:MotionShortcut)=>void,caller:any){
        this.motion = motion
        this.txt_name.text = motion.name
        this.txt_frame_count.text = `frame:${motion.motionSheets.length}`
        this.func = func
        this.caller = caller
    }

    setSelected(val:boolean){
        this.selected.visibility = val?mw.SlateVisibility.Visible:mw.SlateVisibility.Hidden
    }

    private onClicked(){
        this.func.call(this.caller,this)
    }

    private deleteClicked(){
        ModuleService.getModule(ModuleMotionC).deleteMotion(this.motion.name)
    }
}